import React, { Component } from 'react';
import { SortableContainer, SortableHandle, SortableElement, arrayMove } from 'react-sortable-hoc';
import style from './index.scss';

class Sortable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: this.props.items,
    };
  }

  componentWillReceiveProps(nextProps) {
    let { items } = nextProps;
    if (items !== this.state.items) {
      this.setState({ items });
    }
  }

  onSortEnd({ oldIndex, newIndex }) {
    let items = this.state.items;
    let tempArray = [], insertItem;
    for(let index in items) {
      if (Number(index) !== oldIndex) {
        tempArray.push(items[index]);
      } else {
        insertItem = items[index];
      }
    }
    tempArray.splice(newIndex, 0, insertItem);
    let custPrdInfoList = '';
    for(let index in tempArray) {
      if (Number(index) === (tempArray.length - 1)) {
        custPrdInfoList += tempArray[index];
      } else {
        custPrdInfoList += tempArray[index] + ',';
      }
    }
    const scrollTop = this.sortList.scrollTop;
    this.setState({
      items: arrayMove(this.state.items, oldIndex, newIndex),
    }, () => {
      this.props.getInfoList(custPrdInfoList);
      this.sortList.scrollTop = scrollTop;
    });
  }

  sortableList() {
    const DragHandle = SortableHandle((() => <div className="dragIcon">
      <svg className="icon" aria-hidden="true">
        <use xlinkHref="#icon-line" />
      </svg>
    </div>))
    const SortableItem = SortableElement(({ value }) =>
      <li>
        <div className="del-box" onClick={()=>{this.props.iconClick(value)}}>
          <div className="blod">一</div>
        </div>
        <div className="currPair bold">
          <span className="productId">{value}</span>
        </div>
        <DragHandle/>
      </li>);
    const SortableList = SortableContainer(({ items }) => (
      <ul className="sort-list" id="sortableList" ref={x => this.sortList = x}>
        {items.map((value, index) => (
          <SortableItem key={`item-${value}`} index={index} value={value}/>
        ))}
      </ul>
    ));

    return <SortableList
      items={this.state.items}
      helperClass="sortable-active sortable-item"
      lockAxis="y"
      pressDelay={200}
      useDragHandle={true}
      onSortEnd={({ oldIndex, newIndex }) => {
        this.onSortEnd({ oldIndex, newIndex });
      }}/>;
  }

  render() {
    return this.sortableList();
  }
}

export default Sortable;
